<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator=">">
                <el-breadcrumb-item>
                    <i class="el-icon-lx-calendar"></i>用户管理
                </el-breadcrumb-item>
                <el-breadcrumb-item>用户列表</el-breadcrumb-item>
            </el-breadcrumb>
        </div>

        <div class="container">
            <div class="handle-box">
                <el-button
                    type="primary"
                    icon="el-icon-delete"
                    class="handle-del mr10"
                    @click="delAllSelection"
                >批量删除</el-button>
                <el-input v-model="query.username" placeholder="用户名" class="handle-input mr10"></el-input>

                <el-date-picker
                        v-model="query.createTime"
                        type="daterange"
                        align="right"
                        unlink-panels
                        range-separator="至"
                        start-placeholder="注册时间开始"
                        end-placeholder="注册时间截止"
                        value-format="yyyy-MM-dd"
                        :picker-options="pickerOptions">
                </el-date-picker>
                <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
            </div>
            <el-table
                :data="tableData"
                border
                class="table"
                :default-sort = "{prop: 'createTime', order: 'descending'}"
                ref="multipleTable"
                header-cell-class-name="table-header"
                @selection-change="handleSelectionChange"
                @sort-change="handleSortChange"
            >
                <el-table-column type="selection" width="55" align="center"></el-table-column>
                <el-table-column type="index" width="50" label="序号"></el-table-column>
                <el-table-column prop="username" label="用户名"></el-table-column>
                <el-table-column prop="email" label="邮箱"></el-table-column>
                <el-table-column prop="question" label="密码问题"></el-table-column>
                <el-table-column prop="phone" label="手机" align="center">
                </el-table-column>

                <el-table-column sortable="custom" prop="createTime" label="注册时间" width="180px"
                                  >

                </el-table-column>
                <el-table-column label="操作" width="200px" align="center">
                    <template slot-scope="scope">
                        <el-button
                            type="text"
                            icon="el-icon-edit"
                            @click="handleEdit(scope.$index, scope.row)"
                        >编辑</el-button>
                        <el-button
                            type="text"
                            icon="el-icon-delete"
                            class="red"
                            @click="handleDelete(scope.$index, scope.row)"
                        >删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination
                    background
                    layout="total,sizes, prev, pager, next"
                    :current-page="query.pageIndex"
                    :page-size="query.pageSize"
                    :page-sizes="[3, 5, 10, 20]"
                    :total="totalRecords"
                    @current-change="handlePageChange"
                    @size-change="handleSizeChange"
                ></el-pagination>
            </div>
        </div>

        <!-- 编辑弹出框 ：MVVM 架构模式-->
        <el-dialog title="编辑用户" :visible.sync="editVisible" width="30%">
            <el-form ref="editForm" :model="editForm" label-width="70px">
                <el-input type="hidden" v-model="editForm.id"></el-input>
                <el-input type="hidden" v-model="editForm.version"></el-input>
                <el-form-item label="用户名">
                    <el-input v-model="editForm.username"></el-input>
                </el-form-item>
                <el-form-item label="邮箱">
                    <el-input v-model="editForm.email"></el-input>
                </el-form-item>
                <el-form-item label="手机号">
                    <el-input v-model="editForm.phone"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveEdit">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
    import { fetchUserListData,fetchUserUpdateData } from '../../api/index';
    export default {
        name: 'UserList',
        data() {
            return {
                query: {
                    createTime: '',
                    createTimeBegin: '',
                    createTimeEnd: '',
                    username: '',
                    pageIndex: 1,
                    pageSize: 3,
                    orderClause: null
                },
                tableData: [],
                multipleSelection: [],
                delList: [],
                editVisible: false,
                totalRecords: 0,
                editForm: {},
                idx: -1,
                id: -1,
                pickerOptions: {
                    shortcuts: [{
                        text: '最近一周',
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                            picker.$emit('pick', [start, end]);
                        }
                    }, {
                        text: '最近一个月',
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                            picker.$emit('pick', [start, end]);
                        }
                    }, {
                        text: '最近三个月',
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                            picker.$emit('pick', [start, end]);
                        }
                    }]
                }
            };
        },
        created() {
            this.getData();
        },
        methods: {
            // 获取 easy-mock 的模拟数据
            getData() {
                fetchUserListData(this.query).then(res => {
                    const myResp = res.data;
                    console.log(myResp);
                    this.tableData = myResp.data.list;
                    this.totalRecords = myResp.data.total || 50;
                });
            },
            // 触发搜索按钮
            handleSearch() {
                this.$set(this.query, 'pageIndex', 1);
                var createTimeStr = this.query.createTime.toString();
                console.log("createTimeStr:"+createTimeStr);
                var createTimeSplit = createTimeStr.split(",");
                console.log("begin:"+createTimeSplit[0]+",end:"+createTimeSplit[1]);
                this.$set(this.query, 'createTimeBegin', createTimeSplit[0]);
                this.$set(this.query, 'createTimeEnd', createTimeSplit[1]);
                this.getData();
            },
            // 删除操作
            handleDelete(index, row) {
                // 二次确认删除
                this.$confirm('确定要删除吗？', '提示', {
                    type: 'warning'
                })
                    .then(() => {
                        this.$message.success('删除成功');
                        this.tableData.splice(index, 1);
                    })
                    .catch(() => {});
            },
            // 多选操作
            handleSelectionChange(val) {
                this.multipleSelection = val;
            },
            // 排序操作
            handleSortChange(column) {
                console.log("handleSortChange->column:{prop:"+column.prop+",order:"+column.order+"}");
                //调用后台接口进行排序
                var orderField = column.prop == 'createTime' ? "create_time" : column.prop;
                var orderAscDesc = column.order == "ascending" ? "asc" : "desc";
                this.$set(this.query, 'orderClause', orderField + " " + orderAscDesc);
                this.getData();
            },
            delAllSelection() {
                const length = this.multipleSelection.length;
                let str = '';
                this.delList = this.delList.concat(this.multipleSelection);
                for (let i = 0; i < length; i++) {
                    str += this.multipleSelection[i].name + ' ';
                }
                this.$message.error(`删除了${str}`);
                this.multipleSelection = [];
            },
            // 编辑操作
            handleEdit(index, row) {
                /*console.log(row)*/
                this.idx = index;
                this.editForm = row;
                this.editVisible = true;
            },
            // 保存编辑
            saveEdit() {
                this.editVisible = false;
                console.log("saveEdit().......begin:");
                console.log(this.editForm)
                /*return ;*/
                //调用后台的用户更新接口
                fetchUserUpdateData(this.editForm).then(res => {
                    const myResp = res.data;
                    console.log(myResp);
                    const code = myResp.code;
                    if (code == -10) {
                        this.$message.error(`第 ${this.idx + 1} 行数据被他人修改了，请先刷新!`);
                        return false;
                    } else if (code == 200) {
                        this.$message.success(`更新第 ${this.idx + 1} 行成功!`);
                    }
                });

                /*
                console.log(this.editForm)
                this.editForm.username = 'abc';
                this.$set(this.tableData, this.idx, this.editForm);
                */
            },
            // 分页导航
            handlePageChange(val) {
                this.$set(this.query, 'pageIndex', val);
                this.getData();
            },
            handleSizeChange(val) {
                console.log(`每页 ${val} 条`);
                this.$set(this.query, 'pageIndex', 1);
                this.$set(this.query, 'pageSize', val);
                this.getData();
            },
            handleCurrentChange(val) {
                console.log(`当前页: ${val}`);
            }
        }
    };
</script>

<style scoped>
.handle-box {
    margin-bottom: 20px;
}

.handle-select {
    width: 120px;
}

.handle-input {
    width: 300px;
    display: inline-block;
}
.table {
    width: 100%;
    font-size: 14px;
}
.red {
    color: #ff0000;
}
.mr10 {
    margin-right: 10px;
}
.table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
}
</style>
